package server.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import plug.result.ReqPage;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.EssayDao;
import server.model.entity.Essay;

import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("v1/api/essay")
@CrossOrigin(origins = "*")
public class EssayController {
    @Autowired
    EssayDao essayDao;

    @PostMapping("/save")
    public RetResult save(@RequestBody Essay essay) {
        return RetResponse.makeOKRsp(essayDao.save(essay));
    }

    @DeleteMapping("/{id}")
    public RetResult del(@PathVariable String id) {
        essayDao.deleteById(id);
        return RetResponse.makeOKRsp();
    }

    @PostMapping("/all")
    @CrossOrigin(origins = "*")
    public RetResult findAll(@RequestBody ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        Essay entity = JSON.parseObject(req.toJSONString(), Essay.class);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Essay> example = Example.of(entity, matcher);
        Page<Essay> pages = essayDao.findAll(example, pageable);
        List<Essay> pageList = pages.getContent();
        return RetResponse.makeRsp(0, "成功", pageList, (int) pages.getTotalElements());
    }
}
